﻿using System;
using System.Collections.Generic;

using JetBrains.DocumentModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;

namespace FinlogiK.ReSharperContrib
{
	internal sealed class AddStaticQualifierDaemonStageProcess : IDaemonStageProcess
	{
		#region Fields

		private readonly IDaemonProcess _process;

		#endregion

		#region Constructors

		internal AddStaticQualifierDaemonStageProcess(IDaemonProcess process)
		{
			this._process = process;
		}

		#endregion

		#region IDaemonStageProcess Members

        public void Execute(Action<DaemonStageResult> commiter)
        {
            if (!this._process.InterruptFlag)
            {
                var file = this._process.SourceFile.GetPsiFile<CSharpLanguage>() as ICSharpFile;

                if (file != null)
                {
                    var highlights = new List<HighlightingInfo>();
                    var processor = new RecursiveElementProcessor<IReferenceExpression>(referenceExpression =>
                    {
                        if (ArrangeStaticQualifierHelper.IsReferenceToStaticMemberWithoutQualifier(referenceExpression))
                        {
                            DocumentRange documentRange = referenceExpression.GetNavigationRange();
                            highlights.Add(new HighlightingInfo(documentRange, new AddStaticQualifierHighlight(referenceExpression)));
                        }
                    });

                    file.ProcessDescendants(processor);
                    commiter.Invoke((new DaemonStageResult(highlights)));
                }
            }
        }

	    public IDaemonProcess DaemonProcess
	    {
	        get
	        {
                return this._process;
	        }
        }

        #endregion
    }
}